package com.yoshino.leetcode.improve40.sixteenth;

import java.util.ArrayList;
import java.util.List;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode pruneTree(TreeNode root) {
        // 后序遍历
        if (root == null) {
            return null;
        }
        root.left = pruneTree(root.left);
        root.right = pruneTree(root.right);
        // 叶子结点
        if (root.val == 0 && root.left == null && root.right == null) {
            return null;
        }
        return root;
    }

    // 定义一个全局变量记录每个数值，最后再相加，深度遍历
    List<Integer> list;
    public int sumNumbers(TreeNode root) {
        list = new ArrayList<>();
        dfs(root, 0);
        int sum = 0;
        for (Integer s : list) {
            sum += s;
        }
        return sum;
    }

    private void dfs(TreeNode root, Integer sb) {
        if (root == null) {
            return;
        }
//        sb.append(root.val);
        sb = sb * 10 + root.val;
        if (root.left != null) {
            dfs(root.left, sb);
        }
        if (root.right != null) {
            dfs(root.right, sb);
        }
        if (root.left == null && root.right == null) {
//            list.add(sb.toString());
            list.add(sb);
        }
//        sb.deleteCharAt(sb.length() - 1);
        sb /= 10;
    }

}